#coding=utf-8
import sys
sys.path.append("..")
import BAC0
import time
from driver import *

class Bacnet(IOTOSDriverI):
    def InitComm(self,attrs):
        self.setPauseCollect(False)
        self.setCollectingOneCircle=True
        self.online(True)

        #建立连接并且在通路里搜索bacnet设备的ip和设备id
        try:
            self.bacnet=BAC0.connect()
            self.bacnet.whois()

            # 搜索局域网内的bacnet协议设备并且打印出来
            for each in self.bacnet.discoveredDevices:
                deviceName = (self.bacnet.read('%s device %s objectName' % (each[0], each[1])))
                self.deviceAddr = each[0]
                self.debug('Found device : %s at address %s' % (deviceName, self.deviceAddr))
                # 打印设备地址为deviceAddr 的objectList property 前十个
                read_pro = self.deviceAddr + ' device 3 objectList'
                self.debug(self.bacnet.read(read_pro)[:10])

        except Exception as e:
            self.bacnet.disconnect()

    def Collecting(self,dataId):
        try:
            cfgtmp = self.data2attrs[dataId]['config']
            #过滤掉非采集点
            if cfgtmp["param"] == "":
                return ()

            # 过滤采集点
            if 'disabled' in cfgtmp and cfgtmp['disabled'] == True:
                return ()
            else:
                self.debug(self.name(dataId))

            #获取用于数据下发的点
            if  'private' in cfgtmp['param'] and cfgtmp['param']['private']=='write' and 'num' in cfgtmp['param']:
                if "memoryvalue" not in self.data2attrs[dataId]:
                    return ('请下发',)
                else:
                    return (self.data2attrs[dataId]["memoryvalue"],)

            #上传数据点
            if 'objectName' in cfgtmp['param'] and 'num' in cfgtmp['param']:
                data_val = self.deviceAddr + ' ' + str(cfgtmp['param']['objectName'])+' '+str(cfgtmp['param']['num'])+' '+'objectName description presentValue units'
                self.debug(data_val)
                #读取bacnet设备中属性的值
                data = self.bacnet.readMultiple(data_val)
                return (str(data[2]),)

        except Exception as e:
            # 连接会一定时间后断开，需要再次开启
            self.bacnet.disconnect()
            self.bacnet = BAC0.connect()
            self.bacnet.whois()
            return ()

    def Event_setData(self, dataId, value):
        #更改bacnet里面属性的值，一般只能是analoValue属性
        if 'private' in self.data2attrs[dataId]['config']['param']:
            if self.data2attrs[dataId]['config']['param']['private']== 'write':
                data_wri=self.deviceAddr+' '+'analogValue'+' '+ str(self.data2attrs[dataId]['config']['param']['num']) +' presentValue ' + str(value)
                self.debug(data_wri)
                self.bacnet.write(data_wri)
                self.setValue(self.name(dataId), value)

        return json.dumps({'code': 0, 'msg': '', 'data': ''})